﻿Imports System.Net
Imports System.Threading

Public Class Scheduler
    Implements IDisposable

    Private CheckFrequency As Integer = 180
    Private Waithandle As AutoResetEvent = New AutoResetEvent(False)
    Private _Cancelled As Boolean = False
    Private internalSyncLock As Object = New Object

    Public Property Cancelled() As Boolean
        Get
            Return _Cancelled
        End Get
        Set(ByVal value As Boolean)
            _Cancelled = value
        End Set
    End Property
    Private disposedValue As Boolean = False        ' To detect redundant calls


    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)

    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region
    Public Sub Start(ByVal checkFrequency As Integer)
        Me.CheckFrequency = checkFrequency
        Me.Cancelled = False
        Dim t As New Thread(AddressOf Run)
        t.Name = "t_Schedule(Run)"
        t.Start()
    End Sub
    Private Sub Run()
        Debug.Print("-- Running Job --")
        Me.Waithandle.WaitOne(Me.CheckFrequency * 1000, True)
        While Not Cancelled
            Me.PingServer()
            Debug.Print("-- Interval --")
            Me.Waithandle.WaitOne(Me.CheckFrequency * 1000, True)
        End While
    End Sub
    Public Sub StopMe()
        SyncLock Me.internalSyncLock
            If Cancelled Then
                Return
            End If
            Me.Cancelled = True
            Me.Waithandle.Set()
        End SyncLock
    End Sub
    Private Sub PingServer()
        Try
            Debug.Print("--- Pinging Server ---")
            Dim http As WebClient = New WebClient
            Dim Result = http.DownloadString("Http://localhost:49447/default.aspx")
        Catch ex As Exception

        End Try
    End Sub
End Class
